﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyRapid.Launcher
{
    public partial class Loading : Form
    {

        Stopwatch sw = new Stopwatch();
        public Loading()
        {
            InitializeComponent();
        }

        private void UpdateFile()
        {
            try
            {
                string nstr = ReadSetting("version");
                DateTime ntime = DateTime.Parse(nstr);
                WebClient wc = new WebClient();
                wc.Encoding = Encoding.UTF8;
                label1.Text = "正在检查更新...";
                this.Refresh();
                string sjs = wc.DownloadString(ReadSetting("url") + "/GetNew?ntime=" + nstr);
                ApiResult ar = ToObject<ApiResult>(sjs);
                List<Sys_File> sfs = ToObject<List<Sys_File>>(ar.Data);

                progressBar1.Maximum = sfs.Count;
                if (sfs.Count > 0)
                {
                    foreach (Sys_File sf in sfs)
                    {
                        if (ReadSetting("checkFile") == "true")
                        {
                            if (File.Exists(sf.FilePath))
                            {
                                if (File.GetLastWriteTime(sf.FilePath) >= sf.FileDate)
                                {
                                    continue;
                                }
                            }
                        }
                        if (progressBar1.Value < sfs.Count)
                            progressBar1.Value += 1;
                        label1.Text = "正在更新文件：" + sf.FileName + "...";
                        this.Refresh();
                        string fDir = Path.GetDirectoryName(sf.FilePath);

                        if (!string.IsNullOrEmpty(fDir) && !Directory.Exists(fDir))
                        {
                            Directory.CreateDirectory(fDir);
                        }

                        sjs = wc.DownloadString(ReadSetting("url") + "/GetFile?fileName=" + sf.FileName);
                        ar = ToObject<ApiResult>(sjs);
                        List<Sys_File> fds = ToObject<List<Sys_File>>(ar.Data);
                        try
                        {
                            if (fds != null && fds.Count > 0)
                                File.WriteAllBytes(sf.FilePath, fds[0].FileByte);
                        }
                        catch (Exception exf)
                        {
                            label1.Text = "更新文件失败：" + exf.Message;
                        }
                    }
                    //SaveSetting("version", DateTime.Now.ToString());
                    label1.Text = "更新结束：正在启动主程序...";
                }else
                {
                    label1.Text = "未发现更新：正在启动主程序...";
                }

                progressBar1.Style = ProgressBarStyle.Marquee;
            }
            catch (Exception ex)
            {
                label1.Text = "更新失败：" + ex.Message;
                this.Refresh();
            }

        }


        Process process;
        string FormName = "主窗体";
        int WaitSecond = 600;
        private void StartMain()
        {
            //用参数把4个变量传入 
            //分别为
            //1 ProcessName 程序路径
            //2 ImagePath 动画路径
            //3 WaitSecond 最大等待时长
            //4 FormName 启动程序的标识,用于判断程序是否加在完毕   

            string ProcessName = ReadSetting("applicationPath");
            WaitSecond = 600;
            FormName = "用户登录";

            if (File.Exists(ProcessName))
            {
                //启动程序
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = ProcessName;
                processStartInfo.WorkingDirectory = Path.GetDirectoryName(ProcessName);
                process = Process.Start(processStartInfo);
            }
            else
            {
                Environment.Exit(0);
            }
            this.FormBorderStyle = FormBorderStyle.None;
            this.StartPosition = FormStartPosition.CenterScreen;
            sw.Restart();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //这里是用于判断结束 分两种  超时  或  已完成
            if (sw.Elapsed.Seconds > WaitSecond)
                Environment.Exit(0);
            if (process == null)
                Environment.Exit(0);
            if (process.HasExited)
                Environment.Exit(0);
            process.Refresh();
            if (process.MainWindowTitle.Equals(FormName))
                Environment.Exit(0);
            Console.WriteLine(process.MainWindowTitle);
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            //this.Close();
        }


        public string ReadSetting(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings.Get(key);
            }
            catch
            {
                throw;
            }
        }

        public void SaveSetting(string key, string value)
        {
            try
            {
                Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                configuration.AppSettings.Settings[key].Value = value;
                configuration.Save(ConfigurationSaveMode.Modified);
            }
            catch
            {
                throw;
            }
        }

        public JsonSerializerSettings JsonSet()
        {
            JsonSerializerSettings setting = new JsonSerializerSettings();
            setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
            setting.DateFormatString = "yyyy/MM/dd HH:mm:ss";

            //空值处理  
            setting.NullValueHandling = NullValueHandling.Ignore;

            //高级用法九中的Bool类型转换 设置  
            //setting.Converters.Add(new BoolConvert("是,否"));
            return setting;
        }

        public T ToObject<T>(string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json, JsonSet());
        }

        public class Sys_File
        {
            public string FileName { get; set; }
            public DateTime FileDate { get; set; }
            public byte[] FileByte { get; set; }
            public string FilePath { get; set; }
            public string FileFullPath { get; set; }
            public string FileType { get; set; }
        }

        public class ApiResult
        {
            public bool Succeed { get; set; }
            public string Data { get; set; }
            public string Message { get; set; }
        }

        private void Loading_Shown(object sender, EventArgs e)
        {
            UpdateFile();

            this.Refresh();
            timer1.Enabled = true;
            StartMain();
        }
    }
}
